﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StructureMap;
using BonsaiScrum.Bus;
using System.Reflection;

namespace BonsaiScrum.Mvc.Configuration
{
    public class RegisterCommandHandlersInMessageRouter
    {
        private static MethodInfo _createPublishActionWrappedInTransactionMethod;
        private static MethodInfo _registerMethod;

        public static void BootStrap()
        {
            var messageRouter = ObjectFactory.GetInstance<IRouteMessages>();

            new RegisterCommandHandlersInMessageRouter().RegisterCommandHandlers(messageRouter);
        }

        private void RegisterCommandHandlers(IRouteMessages messageRouter)
        {
            _createPublishActionWrappedInTransactionMethod = GetType().GetMethod("CreatePublishActionWrappedInTransaction");
            _registerMethod = messageRouter.GetType().GetMethod("Register");

            var commands = CommandHandlerHelper.GetCommands();
            var commandHandlers = CommandHandlerHelper.GetCommandHandlers();

            foreach (var command in commands)
            {
                IList<Type> commandHandlerTypes;
                if (!commandHandlers.TryGetValue(command, out commandHandlerTypes))
                    throw new ApplicationException(string.Format("No command handler found for the {0} command.", command.FullName));

                foreach (var commandHandler in commandHandlerTypes)
                {
                    var injectedCommandHandler = GetCorrectlyInjectedCommandHandler(commandHandler);
                    var action = CreateTheProperAction(command, injectedCommandHandler);
                    RegisterTheCreatedActionWithTheMessageRouter(messageRouter, command, action);
                }
            }
        }

        private void RegisterTheCreatedActionWithTheMessageRouter(IRouteMessages messageRouter, Type commandType, object action)
        {
            _registerMethod.MakeGenericMethod(commandType).Invoke(messageRouter, new[] { action });
        }

        private object CreateTheProperAction(Type commandType, object commandHandler)
        {
            return _createPublishActionWrappedInTransactionMethod.MakeGenericMethod(commandType, commandHandler.GetType()).Invoke(this, new[] { commandHandler });
        }

        private static object GetCorrectlyInjectedCommandHandler(Type commandHandler)
        {
            return ObjectFactory.GetInstance(commandHandler);
        }

        public Action<TCommand> CreatePublishActionWrappedInTransaction<TCommand, TCommandHandler>(TCommandHandler commandHandler)
            where TCommand : class, ICommand
            where TCommandHandler : ICommandHandler<TCommand>
        {
            return command => ObjectFactory.GetInstance<TransactionHandler<TCommand, TCommandHandler>>().Execute(command, commandHandler);
        }
    }
}
